#!/bin/bash
if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash openfoam-v1906.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* ||  "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* ||  "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1

wget -t 0 -c -P $buildpath https://sourceforge.net/projects/openfoam/files/v1906/OpenFOAM-v1906.tgz
wget -t 0 -c -P $buildpath https://sourceforge.net/projects/openfoam/files/v1906/ThirdParty-v1906.tgz

tar xf $buildpath/OpenFOAM-v1906.tgz -C $buildpath && rm -rf $buildpath/OpenFOAM-v1906.tgz
tar xf $buildpath/ThirdParty-v1906.tgz -C $buildpath && rm -rf $buildpath/ThirdParty-v1906.tgz

cd $buildpath/OpenFOAM-v1906
sed -i "161c DynamicList<char>&& buffer," src/OpenFOAM/db/IOstreams/memory/IListStream.H
sed -i "77c export WM_COMPILER=Clang" etc/bashrc
sed -i "85c export WM_LABEL_SIZE=64" etc/bashrc

source etc/bashrc
./Allwmake -j$(nproc)

cp -r $buildpath/OpenFOAM-v1906 $installpath
cp -r $buildpath/ThirdParty-v1906 $installpath

cat>"$installpath/OpenFOAM-v1906/openfoam_modulefiles"<<EOF
#%Module1.0
conflict openfoam
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set openfoam \$pwd
setenv openfoam \$openfoam
prepend-path PATH \$openfoam/bin
EOF

cat>"$installpath/ThirdParty-v1906/thirdparty_modulefiles"<<EOF
#%Module1.0
conflict thirdparty
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set  thirdparty \$pwd
setenv thirdparty \$thirdparty
prepend-path PATH \$thirdparty
EOF

rm -rf $buildpath/OpenFOAM-v1906
rm -rf $buildpath/ThirdParty-v1906

